package com.qf.hospital.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.system.entity.Cashier;
import com.qf.hospital.system.mapper.CashierMapper;
import com.qf.hospital.system.service.CashierService;
import com.qf.hospital.system.service.PharmacyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class CashierServiceImpl implements CashierService {

    @Autowired
    private CashierMapper cashierMapper;

    @Autowired
    private PharmacyService pharmacyService;

    @Override
    public int findCountByReportIdAndDrugName(Integer reportId, String drugName) {
        return cashierMapper.findCountByReportIdAndDrugName(reportId, drugName);
    }

    @Override
    @Transactional
    public void insert(Cashier cashier) {
        //0. 减库存
        pharmacyService.decrementByPharmacyName(cashier.getDurgNum(), cashier.getDurgName());
        //1. 封装数据
        cashier.setCtime(new Date());
        cashier.setState(1);
        //2. 保存购买的药品信息
        cashierMapper.insertSelective(cashier);
    }

    @Override
    @Transactional
    public void update(Cashier cashier) {
        //0. 减
        pharmacyService.decrementByPharmacyName(cashier.getDurgNum(), cashier.getDurgName());
        //1. 改
        cashierMapper.updateSumAndPriceByReportIdAndDrugName(cashier);
    }

    @Override
    public PageInfo<Cashier> findByReportAndByPage(Integer page, Integer limit, Integer reportId) {
        // p
        PageHelper.startPage(page, limit);
        // rpm
        return new PageInfo<>(cashierMapper.findByReportId(reportId));
    }

    @Override
    @Transactional
    public void deleteCashierById(Integer id) {
        //1. 查询购买药品的信息
        Cashier cashier = cashierMapper.selectByPrimaryKey(id);

        //2. 根据名称添加当前药品库存
        pharmacyService.incremntByPharmacyName(cashier.getDurgName(),cashier.getDurgNum());

        //3. 删除当前记录
        cashierMapper.deleteByPrimaryKey(id);
    }
}
